package com.lzj.admin.controller;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.lzj.admin.model.CaptchaImageModel;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class CaptchaController {
    @Resource
    public DefaultKaptcha defaultKaptcha;

    @RequestMapping(value = "/image",method = RequestMethod.GET)
    public void kaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        response.setDateHeader("EXpires",0);
        response.setHeader("Cache-Control","no-store,no-cache,must-revalidate");
        response.addHeader("Cache-Control","post-check=0,pre-check=0");
        response.setHeader("Prama","no-cache");
        response.setContentType("image/jpeg");
        //验证码信息
        String capTest=defaultKaptcha.createText();
        //将验证码存入session，并设置过期时间
        session.setAttribute("captcha_key",new CaptchaImageModel(capTest,1*60));
        ServletOutputStream os = response.getOutputStream();
        BufferedImage bufferedImage=defaultKaptcha.createImage(capTest);
        //向前端写入
        ImageIO.write(bufferedImage,"jpg",os);
        os.flush();
    }
}
